//
//  LoginViewController.m
//  VMall
//
//  Created by dev on 2017/1/17.
//  Copyright © 2017年 mohao. All rights reserved.
//

#import "LoginViewController.h"
#import "SmsCodeController.h"
#import "UIButton+BCYImage.h"
#import "FbeeCommitBtn.h"
#import "FbeeInputView.h"
#import "UIImage+DataString.h"
#import "FormatChecker.h"
#import "OneLinePickerView.h"

@interface LoginViewController ()<UIGestureRecognizerDelegate>
{
    SucceedBlock callback;
    UIScrollView *mainView;
    UIButton *closeBtn;
    
    FbeeInputView *phoneF;
    UIButton *areaBtn;
    FbeeInputView *picCodeF;
    UIButton *picCode;
    
    FbeeCommitBtn *commit;
    
    OneLinePickerView *picker;
}

@end

@implementation LoginViewController

-(void)dealloc
{
    NSLog(@"LoginViewController dealloc");
    callback = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




-(void)close
{
    [self resignFirstResponderAll];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([KeyBoardManager sharedManager].animationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    });
}

-(instancetype)initWithBlock:(SucceedBlock)block
{
    self = [super init];
    
    if (self) {
        callback = block;
    }
    
    return self;
}

-(void)viewDidDisappear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [phoneF becomeFirstResponder];
    picCodeF.textF.text = @"";
    [self getPicCode];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hiddeBack];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    // 添加观察
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:Notification_LoginSuccess object:nil];
    
    [self buildView];

    
}

-(void)buildView
{
    picker = [[OneLinePickerView alloc] initWithDataArray:@[@"86",@"852",@"886",@"1"
                                                            ,@"81",@"82",@"60",@"61",
                                                            @"65",@"44",@"7"]];
    
    mainView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT)];
    mainView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mainView];
    
    phoneF = [[FbeeInputView alloc] initWithText:NSLocalizedString(@"textLoginPhone", nil)];
    phoneF.centerX = IPHONEWIDTH/2;
    [phoneF setKeyboardType:UIKeyboardTypePhonePad];
    phoneF.top = 190;
    [mainView addSubview:phoneF];
    
    areaBtn = [UIButton makeButton:^(TTButtonExtend *make) {
        make.addTarget(self,@selector(showArea));
        make.addBackGoundColor([UIColor clearColor]);
        make.addTitle(@"+86");
        make.addTitleColor(FBEE_COLOR_BLUE,UIControlStateNormal);
        make.frame = CGRectMake(0, (phoneF.height - 35)/2, 65, 35);
        
    }];
    phoneF.textF.width = phoneF.width - 80;
    phoneF.textF.left = 70;
    [phoneF addSubview:areaBtn];
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(areaBtn.width-5, 10, 1, phoneF.height - 20)];
    line.backgroundColor = UIColorFromRGB(0xE4E4E4);
    [phoneF addSubview:line];
    
    
    
    picCodeF = [[FbeeInputView alloc] initWithText:NSLocalizedString(@"textLoginPicCode", nil)];
    picCodeF.centerX = IPHONEWIDTH/2;
    picCodeF.top = phoneF.bottom + 15;
    [picCodeF setKeyboardType:UIKeyboardTypeASCIICapable];
    [mainView addSubview:picCodeF];
    
    picCode = [UIButton makeButton:^(TTButtonExtend *make) {
        make.addTarget(self,@selector(getPicCode));
        make.addBackGoundColor(FBEE_COLOR_BACKGROUND);
        make.layer.cornerRadius = 35/2;
        make.clipsToBounds = YES;
        make.frame = CGRectMake(picCodeF.width - 80, (picCodeF.height - 35)/2, 70, 35);
    }];
    picCodeF.textF.width = picCodeF.width - picCodeF.textF.left - 80;
    [picCodeF addSubview:picCode];
    
    
    
    commit = [[FbeeCommitBtn alloc] initWithTitle:NSLocalizedString(@"mConfirm", nil)];
    commit.centerX = IPHONEWIDTH/2;
    commit.top = picCodeF.bottom + 65;
    @weakify(self)
    [commit onClick:^{
        @strongify(self)
        [self getSmsCode];
        
    }];
    [mainView addSubview:commit];
    
    
    [self.largeTitle setTitle:NSLocalizedString(@"tNavUCenterQuickLogin", nil)];
    
    closeBtn = [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(0, StatusHeight, 44, 44));
        make.addImage([UIImage imageNamed:@"nav_close_b"],UIControlStateNormal);
        make.addTarget(self,@selector(close));
        [self.largeTitle addSubview:make];
    }];
    [closeBtn setCenterByImageSize:(CGSizeMake(17, 17))];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id sender) {
        @strongify(self)
        [self resignFirstResponderAll];
    }];
    [mainView addGestureRecognizer:tap];
    
    [self bringTitleToFront];
    
}

-(void)resignFirstResponderAll
{
    [phoneF resignFirstResponder];
    [picCodeF resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    float sub = commit.bottom - (IPHONEHEIGHT - [KeyBoardManager sharedManager].keyHeight);
    if (sub > 0) {
        [mainView setContentOffset:CGPointMake(0, sub) animated:YES];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (mainView.contentOffset.y>0) {
        [mainView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    
}

-(void)showArea
{
    [self resignFirstResponderAll];
    
    __weak UIButton *weakBtn = areaBtn;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([KeyBoardManager sharedManager].animationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [picker showInView:self.view selected:^(NSString *selectStr) {
            [weakBtn setTitle:[NSString stringWithFormat:@"+%@",selectStr] forState:UIControlStateNormal];
        }];
    });
    

}

#pragma mark - getData

-(void)getPicCode
{
    [self get:PicCode_URL code:PicCode_URL_Code];
}

-(void)getSmsCode
{
    NSString *mobile = [phoneF getText];
    NSString *code = [picCodeF getText];
    
    if ([mobile isEqualToString:@""] || ![FormatChecker validateMobile:mobile]) {
        [NoticePopHelper showNoticeText:NSLocalizedString(@"textLoginPhone", nil)];
        return;
    }
    
    NSString *area = [areaBtn.titleLabel.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString *url = [NSString stringWithFormat:@"%@?mobile=%@&code=%@&area=%@",SmsCode_URL,mobile,code,area];
    [self get:url code:SmsCode_URL_Code];
}

#pragma mark - request

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    if (code == PicCode_URL_Code) {
        UIImage *img = [UIImage imgWithDataStringArray:[data objectForKey:@"image"]];
        [picCode setImage:img forState:UIControlStateNormal];
    }
    
    if (code == SmsCode_URL_Code) {
        
        NSString *mobile = [phoneF getText];
        NSString *code = [picCodeF getText];
        NSString *area = [areaBtn.titleLabel.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
        
        [self resignFirstResponderAll];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([KeyBoardManager sharedManager].animationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[JumpManager sharedManager] jumpToSmsCodeByPhone:mobile code:code area:area];
        });
    }
    
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    [super requestLogicError:data code:code];
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    
}

-(void)loginSuccess
{
    if (callback) {
        callback();
    }
    
    [self close];
}

@end
